import { createSlice, createAsyncThunk, createEntityAdapter,createSelector } from "@reduxjs/toolkit";
import axios from "axios";
export const TODO_FEATURE_KEY = "todos";
export const loadTodos = createAsyncThunk("todos/loadTodos", (payload) => axios.get(payload).then(response => response.data));
const todosAdapter = createEntityAdapter({
    selectId: todo => todo.cid
});
const { reducer: TodosReducer, actions } = createSlice({
    name: TODO_FEATURE_KEY,
    initialState: todosAdapter.getInitialState(),
    reducers: {
        addTodo: {
            reducer: todosAdapter.addOne,
            prepare: todo => {
                return {
                    payload: { cid: Math.random(), ...todo }
                }
            }
        }
    },
    extraReducers: {
        [loadTodos.pending]: (state, action) => {
            return state
        },
        [loadTodos.fulfilled]: todosAdapter.addMany
    }
});
const { selectAll } = todosAdapter.getSelectors();
export const selectTodoList = createSelector(state=>state[TODO_FEATURE_KEY],selectAll)
export const { addTodo, setTodos } = actions;
export default TodosReducer;